package com.gagakuai.domain.index.datareader;

import com.gagakuai.domain.facts.Fact;
import com.gagakuai.domain.facts.Facts;
import com.gagakuai.domain.index.datasource.MysqlDataSource;
import com.gagakuai.infrastructure.constant.Constants;
import com.gagakuai.infrastructure.mapper.MysqlDataReadMapper;
import com.gagakuai.infrastructure.utils.JacksonUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description: 数据库数据读取器
 * @author: houhong
 * @create: 2024-09-07 14:32
 **/
@Component
public class MysqlDataReader implements DataReader<MysqlDataSource> {


    final Map<Integer, MysqlDataReadMapper> mysqlDataReadMapperMap;

    public MysqlDataReader(List<MysqlDataReadMapper> mysqlDataReadMappers) {
        this.mysqlDataReadMapperMap = buildMapperMap(mysqlDataReadMappers);
    }

    private Map<Integer, MysqlDataReadMapper> buildMapperMap(List<MysqlDataReadMapper> mappers) {
        if (CollectionUtils.isEmpty(mappers)) return new HashMap<>();
        return mappers.stream()
                .collect(Collectors.toMap(MysqlDataReadMapper::getType, readMapper -> readMapper));
    }

    @Override
    public int getType() {
        return Constants.MYSQL_DATA_SOURCE;
    }

    @Override
    public Facts readData(MysqlDataSource dataSource) {

        int tableType = dataSource.getTableType();

        final String indexCode = dataSource.getIndexCode();
        MysqlDataReadMapper readMapper = mysqlDataReadMapperMap.get(tableType);

        Map<String, Object> params = JacksonUtils.objToMap(dataSource);
        List<Object> dataList = readMapper.getData(params);
        Facts facts = new Facts();
        dataList.forEach(data -> {
            Fact<Object> fact = new Fact<>(indexCode, data);
            facts.add(fact);
        });
        return facts;
    }
}
